﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using GameLogic;

namespace Tanks
{
    public partial class MainWindow : Form
    {
        private Game game;
        private Timer timer;
        private Color defaultColor = Color.LightGray;
        private Image buffer;

        public MainWindow()
        {
            InitializeComponent();
            lbPressF2.Visible = true;
            timer = new Timer();
            timer.Interval = Constants.TICK_TIME;
            timer.Tick += RepaintForm;
            this.DoubleBuffered = true;
            this.SetStyle(ControlStyles.AllPaintingInWmPaint |
                          ControlStyles.UserPaint |
                          ControlStyles.DoubleBuffer | ControlStyles.OptimizedDoubleBuffer, true);
        }

        private void RepaintForm(object sender, EventArgs e)
        {
           this.Refresh();
           this.Text = String.Format("Уничтожено: {0}. Запас прочности: {1}", game.KilledCount, game.PlayerHitPoints);
        }


        protected override void OnPaint(PaintEventArgs e)
        {
            if (timer.Enabled)
            {
                if (buffer == null)
                {
                    buffer = new Bitmap(this.ClientSize.Width, this.ClientSize.Height);
                }
                DrawGame(buffer);

                e.Graphics.DrawImageUnscaled(buffer, 0, 0);
            }
        }

        private void DrawGame(Image buffer)
        {
            if (!game.GameOver)
            {
                var graphics = Graphics.FromImage(buffer);
                graphics.Clear(defaultColor);
                game.Tick(graphics);
                graphics.Dispose();
            }
            else 
            {
                if (timer.Enabled)
                {
                    timer.Stop();
                }
                lbLose.Visible = true;
            }
        }


        protected override void OnPaintBackground(PaintEventArgs pevent)
        {

        }

        private void MainWindow_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.F2)
            {
                lbLose.Visible = false;
                lbPressF2.Visible = false;
                if (timer.Enabled)
                {
                    timer.Stop();
                }
                game = new Game(Width, Height);
                timer.Start();
            }
        }
    }
}
